<?php
/**
 * xysc users Version1.0
 * ==================================
 * Copy 2016-2017
 * Web:www.xjh7.com
 * ==================================
 * Author:xjh
 * Date:2016-3-15
*/

class upload{
	private $error;			//上传错误代码
	private $_maxsize;		//表单最大允许值
	private $type;			//类型
	private $typeArr = array('image/jpeg','image/pjpeg','image/png','image/x-png','image/gif');		//类型合集
	private $path;			//目录路径
	private $today;			//今天目录
	private $name;			//文件名
	private $tmp;			//临时文件
	private $linkpath;		//连接路径
	private $linktoday;		//今天目录时间
	public function __construct($_file,$_maxsize){
		if(!is_array($_FILES[$_file]['name'])){
			$this->error = $_FILES[$_file]['error'];
			$this->_maxsize = $_maxsize / 1024;
			$this->type = $_FILES[$_file]['type'];
			$this->path = ROOT_PATH.UPLOAD_URL;
			$this->linktoday = date("Ymd").'/';
			$this->today = $this->path.$this->linktoday;
			$this->name = $_FILES[$_file]['name'];
			$this->tmp = $_FILES[$_file]['tmp_name'];
			$this->checkError(); 
			$this->checkType();
			$this->checkPath();
			$this->moveUpload();
		}else{
			echo "不止上传了一个";
		}
	}
	//返回路径
	public function getPath(){
		$_path = $_SERVER["SCRIPT_NAME"];
		$_dir = dirname(dirname($_path));
 		if($_dir == '\\') $_dir = '/';
		$this->linkpath = $_dir.$this->linkpath;
		return '/xysc'.$this->linkpath;
		
		
	}

	
	//移动文件
	private function moveUpload(){
		if(is_uploaded_file($this->tmp)){
			if(!move_uploaded_file($this->tmp,$this->setNewName())){
				$this->error_info("上传失败");
			}
		}else{
			$this->error_info("临时文件不存在");
		}
	}
	
	
	//设置新文件名
	private function setNewName(){
		$_nameArr = explode('.',$this->name);
		$_postfix = $_nameArr[count($_nameArr)-1];
		$_newname = date("YmdHis").mt_rand(100,1000).'.'.$_postfix;
		$this->linkpath = UPLOAD_URL.$this->linktoday.$_newname;
		return $this->today.$_newname;
	}
	
	//验证目录
	private function checkPath(){
		if(!is_dir($this->path) || !is_writeable($this->path)){
			if(!mkdir($this->path)){
				$this->error_info("创建上传目录失败");
			}
		}
		
		if(!is_dir($this->today) || !is_writeable($this->today)){
			if(!mkdir($this->today)){
				$this->error_info("创建上传子目录失败");
			}
		}
	}
	
	
	//验证类型
	private function checkType(){
		if(!in_array($this->type,$this->typeArr)){
			$this->error_info("上传的文件不是图片");
		}
	}
	
	
	//验证错误
	private function checkError(){
		if(!empty($this->error)){
			switch($this->error){
				case 1:
					$this->error_info("文件太大");
				break;
				case 2:
					$this->error_info('超过'.$this->_maxsize.'KB');
				break;
				case 3:
					$this->error_info("只上传了部分文件");
				break;
				case 4:
					$this->error_info("没有任何文件");
				break;
				default:
					$this->error_info("未知错误");
				break;
			}
		}
	}
	
	
	private function error_info($_string){
		echo "<script>alert('$_string');</script>";
		exit;
	}
}


?>
